#!/bin/bash

### BEGIN INIT INFO
# Provides:             chrome-remote-desktop
# Required-Start:       $remote_fs $syslog
# Required-Stop:        $remote_fs $syslog
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Chrome Remote Desktop service
### END INIT INFO

# /etc/init.d/chrome-remote-desktop: Start and stop Chrome Remote Desktop host daemon.

HOST_PATH=/opt/google/chrome-remote-desktop/chrome-remote-desktop

# Group of users for which Chrome Remote Desktop is enabled. Users are added
# to that group when they start the host for the first time.
CHROME_REMOTING_GROUP=chrome-remote-desktop

test -x $HOST_PATH || exit 0

. /lib/lsb/init-functions

if [ "$(whoami)" = "root" ]; then
  # Extract list of users in the chrome-remoting group.
  USERS=$(getent group $CHROME_REMOTING_GROUP |
          awk -F ':' '{ gsub(",", " ", $4); print $4 }')
else
  USERS=$(whoami)
fi

# Tries to wait for 10 seconds until specified command exits and then kills it.
run_with_timeout() {
  "$@" &
  pid=$!
  local time_left=10
  while [ $time_left -gt 0 ]; do
    (kill -0 $pid 2>/dev/null) || return `wait $pid`
    sleep 1
    time_left=$((time_left - 1))
  done
  (kill -0 $pid 2>/dev/null) || return `wait $pid`

  echo command \"$@\" has timed out >&2
  kill $pid
  return 1
}

# Usage: run_and_ignore_error user action
# Carries out the specified action, ignoring any errors.
run_and_ignore_error() {
  user="$1"
  action="$2"

  set +e
  sudo -u "$user" "$HOST_PATH" "$action"
}

do_start() {
  log_begin_msg "Starting Chrome Remote Desktop host for $1..."
  run_and_ignore_error $1 --start
  log_end_msg $?
}

do_stop() {
  log_begin_msg "Stopping Chrome Remote Desktop host for $1..."
  run_with_timeout run_and_ignore_error $1 --stop
  log_end_msg $?
}

do_reload() {
  log_begin_msg "Reloading Chrome Remote Desktop host configuration for $1..."
  run_and_ignore_error $1 --reload
  log_end_msg $?
}

do_restart() {
  log_begin_msg "Restarting Chrome Remote Desktop host for $1..."
  run_and_ignore_error $1 --stop
  run_and_ignore_error $1 --start
  log_end_msg $?
}

for_each_user() {
  for user in $USERS; do
    $1 $user
  done
}

case "$1" in
  start)
    for_each_user do_start
    ;;

  stop)
    for_each_user do_stop
    ;;

  reload|force-reload)
    for_each_user do_reload
    ;;

  restart)
    for_each_user do_restart
    ;;

  *)
    log_success_msg "Usage: /etc/init.d/chrome-remote-desktop" \
        "{start|stop|reload|force-reload|restart}"
    exit 1
esac

exit 0
